<template>
  <!-- 品牌管理 -->
  <div>
    <!-- 卡片 -->
    <el-card>
      <!-- 添加品牌按钮 -->
      <el-button type="primary" icon="Plus" @click="addTrademark"
        >添加品牌</el-button
      >

      <!-- 表格 -->
      <el-table border :data="trademarkArr" class="table">
        <!-- 序号 -->
        <el-table-column
          label="序号"
          width="80px"
          align="center"
          type="index"
        ></el-table-column>
        <!-- 品牌名称tmName -->
        <el-table-column
          label="品牌名称"
          align="center"
          prop="tmName"
        ></el-table-column>
        <!-- 品牌logo logoUrl -->
        <el-table-column label="品牌logo" align="center" prop="logoUrl">
          <template #default="{ row }">
            <img
              v-if="row.logoUrl"
              :src="row.logoUrl"
              :alt="row.tmName"
              class="logoImg"
            />
            <span v-else>暂无图片</span>
          </template>
        </el-table-column>
        <!-- 品牌操作 -->
        <el-table-column label="品牌操作" align="center">
          <template #default="{ row }">
            <el-button
              type="primary"
              icon="Edit"
              @click="updateTrademark(row)"
            />
            <el-popconfirm
              :title="`你确认要删除${row.tmName}吗?`"
              icon="Delete"
              @confirm="removeTradeMark(row.id)"
              width="230px"
            >
              <template #reference>
                <el-button type="danger" icon="Delete" />
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <el-pagination
        v-model:current-page="pageNo"
        v-model:page-size="limit"
        :page-sizes="[3, 5, 7, 9]"
        layout=" jumper,prev, pager, next, ->,total, sizes"
        :total="total"
        @current-change="getHasTrademark"
        @size-change="sizeChange"
      />
    </el-card>

    <!-- 对话框 -->
    <el-dialog
      v-model="dialogFormVisible"
      :title="trademarkParams.id ? '修改品牌' : '添加品牌'"
      align-center
    >
      <!-- 对话框表单 -->
      <el-form
        style="width: 75%; margin: 10px 0 0 2em"
        label-width="100px"
        label-position="left"
        :model="trademarkParams"
        :rules="rules"
        ref="formRef"
      >
        <el-form-item label="品牌名称" prop="tmName">
          <el-input
            placeholder="请输入品牌名称"
            v-model="trademarkParams.tmName"
          ></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            action="/api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="trademarkParams.logoUrl"
              :src="trademarkParams.logoUrl"
              class="avatar"
              width="178px"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div style="margin-left: 2em">(请上传小于4M的图片类型文件)</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="confirm">确定</el-button>
        <el-button type="danger" @click="cancel">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import {
  reqHasTrademark,
  reqAddOrUpdateTrademark,
  reqDeleteTrademark,
} from "@/api/product/trademark";
import {
  Records,
  tradeMarkResponseData,
  tradeMark,
} from "@/api/product/trademark/type";
import { ElMessage, UploadProps } from "element-plus";

//#region 数据相关定义
// 分页器相关数据
let pageNo = ref<number>(1);
let limit = ref<number>(5);
let total = ref<number>(0);
// 对话框显示隐藏
let dialogFormVisible = ref(false);
// 已有品牌数据
let trademarkArr = ref<Records>([]);
// 接口传递的参数
let trademarkParams = reactive<tradeMark>({
  tmName: "",
  logoUrl: "",
});
// 对话框表单
let formRef = ref();
//#endregion

//获取已有品牌接口函数
const getHasTrademark = async () => {
  let result: tradeMarkResponseData = await reqHasTrademark(
    pageNo.value,
    limit.value
  );
  if (result.code == 200) {
    total.value = result.data.total;
    trademarkArr.value = result.data.records;
  }
};

onMounted(() => {
  getHasTrademark();
});

//分页器改变显示条数函数
const sizeChange = () => {
  pageNo.value = 1;
  getHasTrademark();
};

// 添加品牌按钮的回调
const addTrademark = () => {
  trademarkParams.id = null;
  dialogFormVisible.value = true;
  trademarkParams.logoUrl = "";
  trademarkParams.tmName = "";

  formRef.value?.clearValidate("tmName");
  formRef.value?.clearValidate("logoUrl");
};

// 修改品牌按钮回调
const updateTrademark = (row: tradeMark) => {
  dialogFormVisible.value = true;
  trademarkParams.id = row.id;
  trademarkParams.logoUrl = row.logoUrl;
  trademarkParams.tmName = row.tmName;

  formRef.value.clearValidate("tmName");
  formRef.value.clearValidate("logoUrl");
};

// 删除品牌确认回调
const removeTradeMark = async (id: number) => {
  let result = await reqDeleteTrademark(id);
  if (result.code == 200) {
    ElMessage({
      type: "success",
      message: "删除品牌成功",
    });
    getHasTrademark();
  } else {
    ElMessage({
      type: "error",
      message: "删除品牌失败",
    });
  }
};

// 对话框确认
const confirm = async () => {
  await formRef.value.validate();
  let result = await reqAddOrUpdateTrademark(trademarkParams);
  if (result.code == 200 && trademarkParams.tmName.trim() != "") {
    dialogFormVisible.value = false;
    ElMessage({
      type: "success",
      message: trademarkParams.id ? "修改品牌成功" : "添加品牌成功",
    });
    getHasTrademark();
  } else {
    ElMessage({
      type: "error",
      message: trademarkParams.id ? "修改品牌失败" : "添加品牌失败",
    });
    dialogFormVisible.value = false;
  }
};

// 对话框取消
const cancel = () => {
  dialogFormVisible.value = false;
};

const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (
    rawFile.type == "image/png" ||
    rawFile.type == "image/jpeg" ||
    rawFile.type == "image/gif"
  ) {
    if (rawFile.size / 1024 / 1024 < 4) {
      return true;
    } else {
      ElMessage({
        type: "error",
        message: "上传文件大小应小于4M",
      });
      return false;
    }
  } else {
    ElMessage({
      type: "error",
      message: "上传文件类型必须是PNG|JPG|GIF",
    });
    return false;
  }
};
const handleAvatarSuccess: UploadProps["onSuccess"] = (response) => {
  trademarkParams.logoUrl = response.data;
};

// 对话框表单规则校验
const rules = {
  tmName: [{ required: true, trigger: "blur", message: "请输入品牌名称" }],
  logoUrl: [],
};
</script>

<style scoped lang="scss">
.table {
  margin: 15px auto;
}

.logoImg {
  width: 75px;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>